package com.zrb.mobile;

import java.util.Iterator;
import java.util.Map;

import org.apache.http.Header;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
//import com.amap.api.maps.LocationSource.OnLocationChangedListener;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.zrb.mobile.adapter.CitylistsAdapter;
import com.zrb.mobile.adapter.CitylistsAdapter.ViewHolder;
import com.zrb.mobile.adapter.model.CityDto;
import com.zrb.mobile.adapter.model.CityDtos;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ProgressDialogEx;
import com.zrb.mobile.utility.Tip;
import com.zrb.mobile.utility.ZrbRestClient;

import android.location.Location;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class User_locationsActivity extends BaseActivity implements
		AMapLocationListener, OnClickListener, OnItemClickListener {

	// private OnLocationChangedListener mListener;

	private LocationManagerProxy mLocationManagerProxy;

	CitylistsAdapter mcitylistAdapter;
	Tip progTip;
	ListView mlistview;
	private int parentAreaCode;
	private int checkNum; // 记录选中的条目数量
	private int tmpAreaCode;
	private String areaName;
	private TextView mareaload;
	private boolean isuCenter = false;
	private String name, code;
	private View view;
	private RelativeLayout rl_city_lists_rl;
	private CheckBox city_item_cbs;
	private TextView remind_text;
	private boolean isAllCity = false;

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);

		setContentView(R.layout.u_center_locations);
		if (bundle != null)
			restoreSelf(bundle);
		else {
			parentAreaCode = this.getIntent().getIntExtra("areacode", -1);
			isuCenter = this.getIntent().getBooleanExtra("isucenter", false);
		}

		initView();
		LoadArea();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("areacode", parentAreaCode);
		outState.putBoolean("isucenter", isuCenter);
	}

	private void restoreSelf(Bundle savedInstanceState) {
		parentAreaCode = savedInstanceState.getInt("areacode", -1);
		isuCenter = savedInstanceState.getBoolean("isucenter", false);
	}

	private void initView() {

		// editTextpwd.setText("123456");
		this.findViewById(R.id.title_left_root).setOnClickListener(this);
		TextView txtTitle = (TextView) this.findViewById(R.id.txt_title);
		txtTitle.setText("地  区");
		TextView txtrightTitle = (TextView) this.findViewById(R.id.right_title);
		txtrightTitle.setText("确认");
		txtrightTitle.setVisibility(View.VISIBLE);
		txtrightTitle.setOnClickListener(this);
		mlistview = (ListView) this.findViewById(R.id.listView1);
		view = View.inflate(User_locationsActivity.this,
				R.layout.app_city_all_item, null);
		rl_city_lists_rl = (RelativeLayout) view
				.findViewById(R.id.rl_city_lists_rl);
		city_item_cbs = (CheckBox) view.findViewById(R.id.city_item_cbs);
		remind_text = (TextView) view.findViewById(R.id.remind_text);
		rl_city_lists_rl.setOnClickListener(this);
		remind_text.setText("全国");
		mlistview.addHeaderView(view);
		mlistview.setOnItemClickListener(this);

		if (parentAreaCode == -1)
			init();
		else {

		}
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			this.finish();
			break;

		case R.id.right_title:
			if (code == null || "".equals(code)) {
				Toast.makeText(User_locationsActivity.this, "请选择地区", 0).show();
				return;
			}
			intent = new Intent();
			intent.putExtra("area", name);
			if ("0".equals(code)) {
				intent.putExtra("code", code);
			} else {
				String substring = code.substring(0, code.length() - 1);
				intent.putExtra("code", substring);
			}

			User_locationsActivity.this.setResult(
					android.app.Activity.RESULT_OK, intent);
			User_locationsActivity.this.finish();
			// changeBaseInfo() ;
			break;
		case R.id.layout_arealoading:
			saveArea();
			break;
		case R.id.tv_temp_allarea:
			if (isuCenter)
				return;
			intent = new Intent();
			intent.putExtra("area", "全国");
			intent.putExtra("code", "");
			User_locationsActivity.this.setResult(
					android.app.Activity.RESULT_OK, intent);
			User_locationsActivity.this.finish();
			break;
		case R.id.rl_city_lists_rl:
			//
			city_item_cbs.toggle();
			if (isAllCity) {
				isAllCity = false;
				name = "";
				code = "";
			} else {
				isAllCity = true;
				for (int i = 0; i < mcitylistAdapter.CurrentDatas.size(); i++) {
					if (mcitylistAdapter.getIsSelected().get(i)) {
						mcitylistAdapter.getIsSelected().put(i, false);
						checkNum--;// 数量减1
					}
				}
				mcitylistAdapter.notifyDataSetChanged();
				name = "全国";
				code = "0";
			}
			break;
		}
	}

	private void saveArea() {

		if (mareaload.getTag() == null)
			return;
		CityDto tmpcity = new CityDto();
		String citycode = mareaload.getTag().toString().substring(0, 4) + "00";
		tmpcity.postcode = Integer.parseInt(citycode);
		;
		tmpcity.cityName = mareaload.getText().toString();
		savelocation(tmpcity, true);
	}
 
	
	private void LoadArea() {
		// areaApi/findCityByProvince
		showloading();
		String url = "";
		if (parentAreaCode == -1)
			url = "areaApi/findAllProvince";
		else
			url = "areaApi/findCityByProvince?code=" + parentAreaCode;
		ZrbRestClient.get(url, null, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
				 progTip.Dismiss();
				CommonUtil.showToast("加载数据出错！", User_locationsActivity.this);
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				 progTip.Dismiss();
				String results = new String(arg2);
				try {
					Gson gson = new Gson();
					CityDtos tmpDto = gson.fromJson(results, CityDtos.class);
					if (tmpDto.res == 1) {
						if (mcitylistAdapter == null) {
							mcitylistAdapter = new CitylistsAdapter(
									User_locationsActivity.this, tmpDto.data);
							// mcitylistAdapter.CurrentDatas.addAll(tmpDto.data);
							mlistview.setAdapter(mcitylistAdapter);
						}
					} else
						CommonUtil.showToast(tmpDto.msg,
								User_locationsActivity.this);
				} catch (Exception e) {
					CommonUtil
							.showToast("加载数据出错！", User_locationsActivity.this);
					// System.out.println("eeee!!!!"+e.getMessage());
				}
			}
		});
	}

	/**
	 * 初始化定位
	 */
	private void init() {
		// 初始化定位，只采用网络定位
		mLocationManagerProxy = LocationManagerProxy.getInstance(this);
		mLocationManagerProxy.setGpsEnable(false);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用destroy()方法
		// 其中如果间隔时间为-1，则定位只定一次,
		// 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除
		mLocationManagerProxy.requestLocationData(
				LocationProviderProxy.AMapNetwork, 60 * 1000, 15, this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mLocationManagerProxy != null) {
			// 移除定位请求
			mLocationManagerProxy.removeUpdates(this);
			// 销毁定位
			mLocationManagerProxy.destroy();
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		// TODO Auto-generated method stub
		if (amapLocation != null
				&& amapLocation.getAMapException().getErrorCode() == 0) {
			// 定位成功回调信息，设置相关消息
	 
			mareaload.setText(amapLocation.getProvince() + " "
					+ amapLocation.getCity());
			mareaload.setTag(amapLocation.getAdCode());
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		// 当选择全国和不选择全国进行判断
		if (isAllCity) {
			Toast.makeText(User_locationsActivity.this, "你已经选择了全国", 0).show();
		} else {
			mcitylistAdapter.CurrentDatas.get(arg2 - 1);
			ViewHolder holder = (ViewHolder) arg1.getTag();
			// 改变CheckBox的状态
			if (checkNum == 5) {
				if (holder.rightchk.isChecked() == false) {
					Toast.makeText(User_locationsActivity.this,
							"城市选择大于5个，请选择全国", 0).show();
					return;
				}
			}
			holder.rightchk.toggle();
			// 将CheckBox的选中状况记录下来
			mcitylistAdapter.getIsSelected().put(arg2 - 1,
					holder.rightchk.isChecked());
			// 调整选定条目
			if (holder.rightchk.isChecked() == true) {

				checkNum++;
			} else {
				checkNum--;
			}
			StringBuilder builder1 = new StringBuilder();
			StringBuilder builder2 = new StringBuilder();
			// 遍历地区
			Iterator iter = mcitylistAdapter.getIsSelected().entrySet()
					.iterator();
			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				Boolean ischecked = (Boolean) entry.getValue();
				if (ischecked) {
					// Log.i("sss",entry.getKey().toString());
					int ds = (Integer) entry.getKey();
					Log.i("mcitylistAdapter.CurrentDatas",
							mcitylistAdapter.CurrentDatas.get(ds).id + "");
					builder1.append(mcitylistAdapter.CurrentDatas.get(ds).postcode
							+ ",");
					builder2.append(mcitylistAdapter.CurrentDatas.get(ds).cityName
							+ " ");
				}
				code = builder1.toString();
				name = builder2.toString();
			}

		}
		// Toast.makeText(User_locationsActivity.this, checkNum + "", 0).show();
		// if (!isuCenter) {
		// savelocation(tmpDto, false);
		// return;
		// }
		// if (parentAreaCode == -1) {
		// // 取得ViewHolder对象，这样就省去了通过层层的findViewById去实例化我们需要的cb实例的步骤
		// ViewHolder holder = (ViewHolder) arg1.getTag();
		// // 改变CheckBox的状态
		// holder.rightchk.toggle();
		// // 将CheckBox的选中状况记录下来
		// mcitylistAdapter.getIsSelected().put(arg2,
		// holder.rightchk.isChecked());
		// // 调整选定条目
		// if (holder.rightchk.isChecked() == true) {
		// checkNum++;
		// } else {
		// checkNum--;
		// }
		// Toast.makeText(User_locationsActivity.this, checkNum+"",0).show();
		// areaName = tmpDto.cityName;
		// tmpAreaCode = tmpDto.postcode;
		// Intent intent = new Intent(this, User_locationsActivity.class);
		// intent.putExtra("areacode", tmpAreaCode);
		// intent.putExtra("isucenter", isuCenter);
		// this.startActivityForResult(intent, 100);
		// } else {
		// savelocation(tmpDto, false);
		// }
	}

	private void savelocation(final CityDto mlocation, final boolean isNetloc) {

		if (!isuCenter) {
			Intent intent = new Intent();
			intent.putExtra("area", mlocation.cityName);
			intent.putExtra("code", mlocation.postcode + "");

			User_locationsActivity.this.setResult(
					android.app.Activity.RESULT_OK, intent);
			User_locationsActivity.this.finish();
			return;
		}

		if (AppSetting.curUser == null) {
			Intent intent = new Intent();
			if (isNetloc) {
				intent.putExtra("area", mlocation.cityName);
				intent.putExtra("code", mlocation.postcode + "");
			} else {
				intent.putExtra("cityname", mlocation.cityName);
				intent.putExtra("citycode", mlocation.postcode);
			}
			User_locationsActivity.this.setResult(
					android.app.Activity.RESULT_OK, intent);
			User_locationsActivity.this.finish();
			return;
		}
 	}

	private void showloading() {
		if (progTip == null)
			progTip = ProgressDialogEx.Show(this, " title", "正在加载中...", true,
					true);
		else
			progTip.Show("正在加载中...");
	}

	// 回调方法，从第二个页面回来的时候会执行这个方法
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// 根据上面发送过去的请求吗来区别
		if (resultCode == android.app.Activity.RESULT_OK) {
			switch (requestCode) {
			case 100:
				String cityname = data.getStringExtra("cityname");
				int cityCode = data.getIntExtra("citycode", -1);
				Intent intent = new Intent();
				intent.putExtra("area", areaName + " " + cityname);
				intent.putExtra("code", tmpAreaCode + "," + cityCode);
				User_locationsActivity.this.setResult(
						android.app.Activity.RESULT_OK, intent);
				User_locationsActivity.this.finish();
				break;

			default:
				break;
			}
		}
	}

	/*
	 * @Override public void onClick(View v) { // TODO Auto-generated method
	 * stub switch (v.getId()) {
	 * 
	 * 
	 * break; case R.id.button_register: Intent it = new Intent(this,
	 * User_registerStep1.class); startActivity(it); break; }
	 * 
	 * }
	 */

}
